// let URL = "https://step2step.cn/mg/video/download";
let URL = "https://jsz315.xyz/ns/video/download";

// let URL = "http://49.51.69.50:3000/video/download";
// import { URL } from "./config";

console.log("inject js");

window.onload = function () {
    setTimeout(() => {
        console.log("search", location.search);
        let url = decodeURIComponent(location.search.split("=").pop());
        // document.getElementById("main_page_text").value = url;
        start(url);
    }, 900);
}


async function start(url) {
    console.log("start")
    document.title = "开始";
    await sleep(200);
    var t = document.getElementById("main_page_text");
    t.value = url;
    await sleep(1200);
    // alert(t.value);
    var btn = document.getElementById("submit");
    btn.click();

    let nodes = [];
    let timer = 0;
    do {
        await sleep(5000);
        nodes = document.querySelectorAll(".result_overlay a");
        if (++timer > 4) {
            document.title = "失败";
            return;
        }
    }
    while (nodes.length == 0);

    let arr = [...nodes];
    arr.pop();
    arr = arr.map(i => {
        console.log(i.innerText)
        console.log(i.href)
        let t = i.innerText.match(/(\d+)x\d+/);
        return {
            num: Number(t[1]),
            size: t[0],
            url: i.href

        }
    })
    arr.sort((a, b) => b.num - a.num);
    console.log(arr);
    document.title = "完成";
    let link = arr[0].url;
    post({
        video: link,
        src: url,
        size: arr[0].size
    });

    // window.open(link, "_blank");

    // history.back();
}

function sleep(n) {
    return new Promise(resolve => {
        setTimeout(resolve, n);
    })
}

function post(param) {
    fetch(URL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(param)
    })
        .then(response => response.json())
        .then(res => {
            console.log("res download", res)
            if (res.tip) {
                msg(res.tip);
            } else {
                msg("保存失败");
            }
        })
        .catch(error => {
            msg("保存错误");
        });
}

function msg(str) {
    console.log(str);
}

// Jsz.04005301!
// 49.51.69.50